import paho.mqtt.client as mqtt

from app.iot_mqtt.iot_config import device_config


mqtt_client = None
def init_mqtt():
    """初始化MQTT连接"""
    global mqtt_client

    mqtt_client = mqtt.Client(client_id=device_config["client_id"])
    mqtt_client.username_pw_set(device_config["username"], device_config["password"])
    from app.iot_mqtt.iot_funciton import on_connect, on_message, on_disconnect, log
    mqtt_client.on_connect = on_connect
    mqtt_client.on_message = on_message
    mqtt_client.on_disconnect = on_disconnect

    try:
        mqtt_client.connect(device_config["hostname"], device_config["port"], 60)
        mqtt_client.loop_start()
        log("华为云IoT平台MQTT客户端已启动")
        log(f"设备ID: {device_config['username']}")
        log(f"服务器地址: {device_config['hostname']}:{device_config['port']}")
    except Exception as e:
        log(f"MQTT连接初始化失败: {str(e)}")

# init_mqtt()
